package com.tianmao.servlet;

import com.tianmao.dao.ProductDao;
import com.tianmao.model.Product;
import com.tianmao.util.CartUtil;

import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 点击“加入购物车”按钮，添加产品到购物车，该Servlet负责处理添加到购物车的请求
 *
 */
@WebServlet("/cs")  //购物车 shopping cart
public class CartServlet extends HttpServlet {

    ProductDao productDao = new ProductDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取请求参数
        String productId = req.getParameter("pid");
        // 获取商品信息
        Product product = productDao.findProductById(productId);
        String productName = product.getProductName();
        float productPrice = product.getProductPrice();
        String productUnit = product.getProductUnit();
        int productQty = Integer.parseInt(req.getParameter("qty"));
        String productImg = product.getProductImg();

        // 将信息封装
        Product p;
        p = new Product(productId,productName,productPrice,productUnit,productQty,productImg);

        // 将产品对象封装到ArrayList中
        List list = null;


        // 在会话期间维护购物车列表
        HttpSession httpSession = req.getSession();
        if(httpSession.getAttribute("cartList") == null) {
            list = new ArrayList<Product>();
            System.out.println(list);
            list = CartUtil.productAdd(p,list);
            httpSession.setAttribute("cartList", list);
        }else {

            list = (List<Product>) httpSession.getAttribute("cartList");
            list = CartUtil.productAdd(p,list);
        }
        // 加入购物车后, 跳转至购物车页面
        resp.sendRedirect("cart.jsp");
//        如何实现点击加入购物车, 而不跳转到购物车页面 resp.sendRedirect("ps?pid=" + productId);
    }
}
